<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物体移动</title>

    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .box {
            width: 50px;
            height: 50px;
            background-color: red;
            position: absolute;
            left: 50px;
            top: 50px;
            cursor: move;
        }
    </style>
</head>
<body>

    <div class="box"></div>

   <script>
      var box = document.querySelector('.box');
      var isDown = false;
      var startX, startY;
      box.addEventListener('mousedown', function(event) {
          isDown = true;
          startX = event.clientX - box.offsetLeft;
          startY = event.clientY - box.offsetTop;  
          document.addEventListener('mousemove', onMouseMove);
          document.addEventListener('mouseup', onMouseUp);
          function onMouseMove(event) {
              if (!isDown) return;
              let moveX = event.clientX - startX ;
              let moveY = event.clientY - startY;
              if(moveX > 0 && moveX < window.innerWidth - box.offsetWidth)   box.style.left = moveX + 'px';
              if(moveY > 0 && moveY < window.innerHeight - box.offsetHeight)   box.style.top = moveY + 'px';
          }
          function onMouseUp() {
                isDown = false;
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
                console.log(box.style.left, box.style.top);
          }
             
      })
   </script>
    
</body>
</html>